package com.example.yibu.modelConfig;

import com.example.yibu.yibService.AiTestVService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletionException;
import java.util.concurrent.Semaphore;

@Slf4j
@Service
public class AsyncService {
    @Autowired
    private ConfigQueue configQueue;
    @Autowired
    private AiTestVService aiTestVService;
    //设置许可数量
    private static final Semaphore semaphore = new Semaphore(2);

    public void processQueue() {
        try {
            while (true) {
                QueueEntity queueTask = configQueue.getQueueTask();
                QueueEntity task = configQueue.getQueueTask();

                //第一个队列任务
                if (queueTask != null) {
                    log.info("尝试获取信号量许可: {}", queueTask.getRequestId());
                    semaphore.acquire();
                    log.info("获取信号量许可成功: {}", queueTask.getRequestId());
                    try {
                        //执行任务
                        aiTestVService.startTask(queueTask,semaphore::release);
                    } catch (Exception e) {
                        log.error("数据提交失败: {}" , queueTask, e);
                        semaphore.release();
                    }
                } else {
                    try {
                        Thread.sleep(1000); // 队列为空时休眠1秒
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }

                //第二个队列任务
                if (task != null) {
                    log.info("尝试获取信号量许可: {}", task.getRequestId());
                    semaphore.acquire();
                    log.info("获取信号量许可成功: {}", task.getRequestId());
                    try {
                        //执行任务
                        aiTestVService.startTask(queueTask,semaphore::release);
                    } catch (Exception e) {
                        log.error("数据提交失败: {}" , queueTask, e);
                        semaphore.release();
                    }
                } else {
                    try {
                        Thread.sleep(1000); // 队列为空时休眠1秒
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }


            }
        } catch (Exception e) {
            throw new RuntimeException(e.getCause());
        } finally {
            semaphore.release();
        }
    }

}
